import {mutableHandlers} from "./handler.js";
import {isObject} from "../shared/index.js";

export function reactive(target) {
    return createReactiveObject(target);
}

export let ReactiveFlags;
(function (ReactiveFlags) {
    ReactiveFlags["IS_REACTIVE"] = "__v_isReactive";
})(ReactiveFlags || (ReactiveFlags = {}));

// 做一层映射，解决相同对象重复 reactive 的情况
const reactiveMap = new WeakMap(); // 防止内存泄漏
// 响应式对象核心逻辑

function createReactiveObject(target) {
    if (!isObject(target)) {
        return;
    }
    // 已经是代理对象直接返回代理对象
    if (target[ReactiveFlags.IS_REACTIVE]) {
        return target;
    }

    // 相同对象返回的永远是同一个代理对象
    let existingProxy = reactiveMap.get(target);
    if (existingProxy) {
        return existingProxy;
    }
    // 返回代理对象
    const proxy = new Proxy(target, mutableHandlers);
    reactiveMap.set(target, proxy);
    return proxy;
}

export function isReactive(source) {
    return !!(source && source[ReactiveFlags.IS_REACTIVE])
}

export function toReactive(source) {
    return isObject(source) ? reactive(source) : source
}
